/* mixin */
import fieldMixin from '@src/mixins/fieldMixin';
import FormDesignMixin from '@src/mixins/formDesign';
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
/* util */
import * as FormUtil from '@src/component/form/util';
import _ from 'lodash';
import { t } from '@src/locales'

import { contractFieldList, contractFieldSave } from '@src/api/ContractApi'

export default {
  name: 'contract-fields-setting',
  mixins: [fieldMixin, FormDesignMixin],
  props: {
    mode: {
      type: String,
      default: 'contract'
    },
    // 合同模板id
    contractTemplateId: {
      type: String,
      default: ''
    }
  },
  data(){
    return {
      init: false,
      pending: false,
      visible: false,
      fields: [], // 表单字段
      maxField: 100,
    }
  },
  watch: {
    visible(val) {
      if(!val) this.$emit('success');
    }
  },
  methods: {
    async initialize() {
      this.pending = true;

      await this.getContractFields()

      this.init = true;
      this.pending = false; 
    },
    async getContractFields() {
      try {
        let res = await contractFieldList({
          templateId: this.contractTemplateId
        });
        if (res.code === 0) {
          this.fields = this.toFormField(res.result || [])
        }
      } catch (error) {
        console.log('fetch contract getContractFields => err', error);
      }
    },
    // 打开表单设置弹窗
    open() {
      this.init = false;
      this.visible = true;
      this.initialize();
    },
    // 将后端字段转换成设计器可接受的字段
    toFormField(fields = []) {
      let sortedFields = fields.sort((a, b) => a.orderId - b.orderId);
      fields.forEach((field) => {
        field.subFormFieldList && field.subFormFieldList.sort((a, b) => a.orderId - b.orderId);
      })
      
      return FormUtil.toFormField(sortedFields);
    },
    // 将字段转换成后端可接收的字段
    packToField(origin) {
      let fields = FormUtil.toField(origin);

      fields.forEach((field, index) => {
        field.tableName = this.mode;
        field.orderId = index;
        // 保存时是这个字段，不是subFormFieldList
        field.childrenForm && field.childrenForm.forEach((subField, subIndex) => {
          subField.tableName = this.mode;
          subField.orderId = subIndex;
        })
      })

      return fields;
    },
    /** 
    * @description 提交表单字段设置
    */
    async submit() {
      try {
        let fields = this.packToField(this.fields);
        
        // 表单字段格式校验
        let message = FormUtil.validate(fields);
        if(!FormUtil.notification(message, this.$createElement)) return;

        this.pending = true;

        fields.forEach(field => {
          // 服务端要求defaultValue默认传个空字符，为避免影响，不在FormField做处理，单独处理下
          field.defaultValue = field.defaultValue || ''
          field.childrenForm && field.childrenForm.forEach(v => {
            v.defaultValue = v.defaultValue || ''
          })

          field.templateId = this.contractTemplateId;

          if(!field.parentFieldId) {
            field.parentFieldId = ''
          }
        })

        let result = await contractFieldSave(fields);
        let isSuccess = result.code === 0;

        if(isSuccess) {
          this.visible = false;
          this.getContractFields()
          this.$message.success(t('common.base.moduleFieldUpdateSuccess', {module: ''}))
        } else {
          this.$message.error(result.message)
        }
        
      } catch (error) {
        console.error(error)
        this.$message.error(t('common.base.moduleFieldUpdateError', {module: ''}))
      }

      this.pending = false;
    }
  },
  mounted() {
  }
}